package game.zqll.mod;

import java.net.URL;
import java.net.URLClassLoader;
import java.util.List;

public class ModClassLoader extends URLClassLoader {
    final ModMeta modMeta;
    private List<ClassLoader> dependencyLoaders;

    public ModClassLoader(URL modJarUrl, List<ClassLoader> dependencyLoaders) throws Exception {
        super(new URL[]{modJarUrl}, ClassLoader.getSystemClassLoader());
        this.dependencyLoaders = dependencyLoaders;
        this.modMeta = ModMeta.readFromJar(modJarUrl.getPath());
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        try {
            // 先自己找
            return super.findClass(name);
        } catch (ClassNotFoundException e) {
            // 再去依赖的 classloader 里找
            for (ClassLoader dep : dependencyLoaders) {
                try {
                    return dep.loadClass(name);
                } catch (ClassNotFoundException ignore) {
                }
            }
            throw e;
        }
    }

    public String getModId() {
        return modMeta.modId;
    }

    public String getMainClass() {
        return modMeta.mainClass;
    }

}
